package cn.yl.order.server.service.impl;

import cn.yl.api.server.util.JwtUtil;
import cn.yl.order.server.entity.PayOrder;
import cn.yl.order.server.entity.UserCourseOrder;
import cn.yl.order.server.entity.vo.PayOrderVo;
import cn.yl.order.server.entity.vo.UserCourseOrderVo;
import cn.yl.order.server.mapper.UserCourseOrderMapper;
import cn.yl.order.server.service.PayOrderService;
import cn.yl.order.server.service.UserCourseOrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.Claims;
import org.apache.shardingsphere.core.strategy.keygen.SnowflakeShardingKeyGenerator;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户课程订单表 服务实现类
 * </p>
 *
 * @author yl
 * @since 2022-04-22
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserCourseOrderServiceImpl extends ServiceImpl<UserCourseOrderMapper, UserCourseOrder> implements UserCourseOrderService {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private PayOrderService payOrderService;

    @Override
    public List<UserCourseOrder> getOKOrderCourseIds(String jwt) {
        Claims claims = jwtUtil.parseJWT(jwt);
        QueryWrapper<UserCourseOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 20);
        wrapper.eq("user_id", Integer.parseInt(claims.getId()));
        return this.list(wrapper);
    }

    @Override
//    @Async("orderExecutor")
    public boolean saveOrder(PayOrderVo payOrderVo) {
        boolean flag = false;
//        Claims claims = jwtUtil.parseJWT(jwt);
//        int userId = Integer.parseInt(claims.getId());
        int userId = payOrderVo.getUserId();

        //查询UserCourseOrder
        QueryWrapper<UserCourseOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("source_type", 1).eq("course_id", payOrderVo.getCourseId());
        UserCourseOrder one = this.getOne(wrapper);

        UserCourseOrder userCourseOrder = new UserCourseOrder();
        userCourseOrder.setCourseId(payOrderVo.getCourseId()).
                setUserId(userId).
                setSourceType(1).
                setStatus(0);
        PayOrder payOrder = new PayOrder();
        BeanUtils.copyProperties(payOrderVo, payOrder);
        payOrder.setUserId(userId).setStatus(1).setChannel("weChat");
        flag = payOrderService.save(payOrder);
        if (flag) {
            userCourseOrder.setOrderNo(payOrderVo.getOrderNo());
            // 如果存在 userId，type，courseId,这个订单
            if (one != null) {
                one.setOrderNo(payOrderVo.getOrderNo()).setStatus(0);
                this.updateById(one);
                return true;
            }
            userCourseOrder.setCodeUrl(payOrderVo.getCodeUrl());
            flag = this.save(userCourseOrder);
        }
        return flag;
    }

    @Override
    public List<String> getTimeOutOrder(Integer time) {
        QueryWrapper<UserCourseOrder> wrapper = new QueryWrapper<>();
        Instant instant = Instant.now().minus(Duration.ofMinutes(time)).plusMillis(TimeUnit.HOURS.toMillis(8));
        wrapper.le("create_time", instant);
        wrapper.in("status",0,10);
        List<UserCourseOrder> list = this.list(wrapper);
        if (list != null) {
            ArrayList<String> timeOutOrderIdList = new ArrayList<>();
            list.forEach(userCourseOrder -> timeOutOrderIdList.add(userCourseOrder.getOrderNo()));
            return timeOutOrderIdList;
        }
        return null;
    }

}
